package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsCategoryMapper;
import com.qf.mapper.DtsGoodsMapper;
import com.qf.pojo.DtsCategory;
import com.qf.pojo.DtsGoods;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsCategoryService;
import com.qf.service.DtsStorageService;
import com.qf.service.DtsStorageService;
import com.qf.util.ResponseUtil;
import com.qf.vo.CatVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 千峰教育
 * @Company http://www.mobiletrain.org/
 * @Version 1.0
 */
@Service
public class DtsCategoryServiceImpl implements DtsCategoryService {

    @Autowired
    DtsCategoryMapper categoryMapper;

    @Autowired
    DtsStorageService storageService;

    @Value("${aliyun.oss.endpoint}")
    String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    String accessKeySecret;
    @Value("${aliyun.oss.bucketName}")
    String bucketName;

    /**
     * 二级分类 id
     * @param cateId
     * @return
     */
    @Override
    public List<Integer> findCategoryId(Integer cateId) {

        DtsCategory category =  categoryMapper.selectById(cateId);

        Integer pid = category.getPid();

        List<Integer> ids = new ArrayList<>();
        ids.add(pid);
        ids.add(cateId);

        return ids;
    }

    @Override
    public List<CatVo> findCategoryList() {
        //1. 首先查询一级 分类列表
        LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsCategory::getDeleted, false);
        wrapper.eq(DtsCategory::getPid, 0);


        List<DtsCategory> categoryList = categoryMapper.selectList(wrapper);

        if(categoryList != null){
            List<CatVo> catVoList = categoryList.stream().map(category -> {
                //一个分类对象 对应一个 CatVo对象
                CatVo catVo = new CatVo();
                catVo.setValue(category.getId());
                catVo.setLabel(category.getName());

                //查询二级分类列表
                LambdaQueryWrapper<DtsCategory> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(DtsCategory::getDeleted, false);
                wrapper1.eq(DtsCategory::getPid, category.getId());
                List<DtsCategory> categories = categoryMapper.selectList(wrapper1);
                if(categories != null){
                    List<CatVo> catVoList1 = categories.stream().map(category1 -> {
                        //一个分类对象 对应一个 CatVo对象
                        CatVo catVo1 = new CatVo();
                        catVo1.setValue(category1.getId());
                        catVo1.setLabel(category1.getName());
                        return catVo1;
                    }).collect(Collectors.toList());

                    //设置 二级分类列表
                    catVo.setChildren(catVoList1);
                }

                return catVo;
            }).collect(Collectors.toList());

            return catVoList;
        }

        return null;
    }

    @Override
    public boolean isExists(Integer categoryId) {

        LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsCategory::getDeleted, false);
        wrapper.eq(DtsCategory::getId, categoryId);

        int count = categoryMapper.selectCount(wrapper);
        return count != 0;
//        if(count == 0){
//            return false;
//        }
//        return true;
    }


    @Override
    public IPage<DtsCategory> queryPage(Integer page, Integer limit, Integer id, String name, String sort, String order) {

        IPage<DtsCategory> iPage = new Page<>(page, limit);

        QueryWrapper<DtsCategory> wrapper = new QueryWrapper<>();

        if(!StringUtils.isEmpty(id)){
            wrapper.like("id", id);
        }

        if(!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }

        if(order.equalsIgnoreCase("desc")){
            wrapper.orderByDesc(sort);
        }else {
            wrapper.orderByAsc(sort);
        }

        iPage = categoryMapper.selectPage(iPage, wrapper);

        return iPage;
    }

    @Override
    public List<CatVo> findCategoryL1() {

        LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsCategory::getDeleted, false);
        wrapper.eq(DtsCategory::getPid, 0);

        List<DtsCategory> categoryList = categoryMapper.selectList(wrapper);

        if(categoryList != null){
            List<CatVo> cateVoList = categoryList.stream().map(category -> {
                //一个分类对象  对应一个catvo对象
                CatVo catVo = new CatVo();
                catVo.setValue(category.getId());
                catVo.setLabel(category.getName());

                return catVo;
            }).collect(Collectors.toList());

            return cateVoList;
        }
        return null;
    }

    @Override
    public Object update(DtsCategory category) {


        DtsCategory category2 = categoryMapper.selectById(category);

        if(!category.getName().equals(category2.getName())){
            LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DtsCategory::getName,category.getName());
            DtsCategory category1 = categoryMapper.selectOne(wrapper);
            if(category1.getName()!=null){
                return ResponseUtil.fail(-1,"商品类目已存在");

            }
        }

        DtsCategory oldCategory = categoryMapper.selectById(category);
        DtsStorage storage = null;
        if(StringUtils.isEmpty(oldCategory.getIconUrl())){
            storage =storageService.findStorage(oldCategory.getIconUrl());
            if(!oldCategory.getIconUrl().equals(category.getIconUrl())){
                if(storage != null){
                    storageService.deleteById(storage);
                }
            }
        }

        if(oldCategory.getPicUrl() != null){
            storage=storageService.findStorage(oldCategory.getPicUrl());
            if(!oldCategory.getPicUrl().equals(category.getPicUrl())){
                if(storage != null){
                    storageService.deleteById(storage);
                }
            }
        }

        category.setUpdateTime(new Date());
        categoryMapper.updateById(category);
       return ResponseUtil.ok(category);
    }

    @Override
    public Object insert(DtsCategory category) {

        LambdaQueryWrapper<DtsCategory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DtsCategory::getName,category.getName());
        DtsCategory category1 = categoryMapper.selectOne(wrapper);
        if(category1!=null){
            return ResponseUtil.fail(-1,"商品类目已存在");

        }

        category.setAddTime(new Date());
        category.setUpdateTime(new Date());

        categoryMapper.insert(category);

        return ResponseUtil.ok(category);
    }

    @Autowired
    DtsGoodsMapper goodsMapper;
    @Override
    public Object delete(DtsCategory category) {

        LambdaQueryWrapper<DtsGoods> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DtsGoods::getCategoryId,category.getId());
        DtsGoods goods = goodsMapper.selectOne(wrapper1);

        if(goods!=null){
            return ResponseUtil.fail(-1,"该类目正在使用不能删除");
        }


        if(category.getPid() == 0){

            QueryWrapper<DtsCategory> wrapper = new QueryWrapper<>();
            wrapper.eq("pid", category.getId());
            wrapper.eq("deleted", false);

            List<DtsCategory> list = categoryMapper.selectList(wrapper);
            if(list.size()>0){
                return ResponseUtil.fail(-1,"存在二级类目，不能删除");
            }

        }
        DtsStorage storage = null;
        if(category.getIconUrl() != null){
            storage =storageService.findStorage(category.getIconUrl());
            if(storage != null){
                storageService.deleteById(storage);
            }
        }

        if(category.getPicUrl() != null){
            storage=storageService.findStorage(category.getPicUrl());
            if(storage != null){
                storageService.deleteById(storage);
            }
        }

        int i = categoryMapper.deleteById(category.getId());

        if(i>0){
            return ResponseUtil.ok();
        }
        return ResponseUtil.badArgument();
    }
}
